<!DOCTYPE html>
<html>
<head>
<title>Media Capture from DOM Elements (video/audio) Browser Test</title>
</head>
<body>
  <div> Capture and playback from video/audio elements.</div>
  <video id="video"></video>
  <audio id="audio"></audio>
</body>
<script type="text/javascript" src="webrtc_test_utilities.js"></script>
<script>

'use strict';

const NUMBER_OF_EVENTS_TO_RECORD = 5;

function testCaptureFromMediaElement(filename,
                                     has_video,
                                     has_audio,
                                     use_audio_tag) {
  const element = use_audio_tag ? document.getElementById('audio')
                                : document.getElementById('video');
  assertTrue(element, 'Error resolving tag');

  return new Promise((resolve, reject) => {
    element.onerror = function(e) {
      reject(new Error("error playing back [" + filename + "] " + e));
    };

    element.preload = "auto"; // Ensures element doesn't suspend on load.
    element.src = filename;

    var recorded_events = 0;
    element.onloadedmetadata = function() {
      const stream = element.captureStream();
      assertTrue(stream, 'Error creating MediaStream');
      assertEquals(has_video, stream.getVideoTracks().length);
      assertEquals(has_audio, stream.getAudioTracks().length);

      const recorder = new MediaRecorder(stream);
      assertTrue(recorder, 'Error creating recorder out of the MediaStream');

      recorder.onerror = function(e) {
        reject(new Error("error recording [" + filename + "] " + e));
      };

      recorder.ondataavailable = function(event) {
        if (++recorded_events > NUMBER_OF_EVENTS_TO_RECORD || element.ended)
          resolve(logSuccess());
      };

      element.onended = function() {
        console.log('Playback ended before event count saturated.');
        // This will trigger a final ondataavailable().
        recorder.stop();
      };

      recorder.start(0);
      element.play();
    };
  });
}

</script>
</body>
</html>
